import UserInfoForm from '@/components/UserForm/UserInfoForm';
import PasswordForm from '@/components/UserForm/PasswordForm';
import { Alert, Spin, Tag, Tree } from 'antd';
import ProForm from '@ant-design/pro-form';

export default (props: { isPersonal: boolean; isAdd: boolean }) => {
  const { isPersonal, isAdd } = props;

  return (
    <>
      <UserInfoForm isPersonal={isPersonal} isAdd={isAdd} />
      {isAdd && <PasswordForm isPersonal={false} />}
    </>
  );
};

export type TreeData = {
  title: string;
  key: string;
  isLeaf?: boolean;
  children?: TreeData[];
  checkable: boolean;
  selectable: boolean;
  pKey: string;
  pTitle: string;
};

const RoleFormItem = (props: {
  value?: UserGroupEntity[];
  onChange?: (value: UserGroupEntity[]) => void;
  roleTree?: TreeData[];
}) => {
  const { value = [], onChange, roleTree } = props;

  if (!roleTree) {
    return (
      <div style={{ width: '100%', display: 'flex', justifyContent: 'center' }}>
        <Spin spinning={true} />
      </div>
    );
  }

  return (
    <>
      {value.length > 0 && (
        <Alert
          style={{ marginBottom: 6 }}
          message={
            <div>
              已分配：
              {value.map((item) => (
                <Tag style={{ fontSize: 14, padding: '4px 8px' }} key={item.id}>
                  {item.path.substring(1)}
                </Tag>
              ))}
            </div>
          }
          type="info"
        />
      )}
      <Tree
        defaultExpandedKeys={roleTree.map((item) => item.key)}
        checkedKeys={value.map((item) => item.id)}
        checkable
        treeData={roleTree}
        onCheck={(_, info) => {
          const { checkedNodes } = info;
          if (onChange) {
            onChange(
              checkedNodes.map((item) => ({
                id: item.key,
                name: item.title,
                path: `/${item.pTitle}/${item.title}`,
                tenant_id: item.pKey,
                tenant_name: item.pTitle,
              })),
            );
          }
        }}
      />
    </>
  );
};

export const UpdateRolesForm = (props: { roleTree?: TreeData[] }) => {
  return (
    <ProForm.Item name="groups">
      <RoleFormItem roleTree={props.roleTree} />
    </ProForm.Item>
  );
};
